<?php

require_once(WSB_MODULES_PATH .'sherpa/models/BaseGateway.php');
require_once(WSB_MODULES_PATH .'sherpa/models/Categories.php');
require_once(WSB_MODULES_PATH .'sherpa/models/Category.php');

class Sherpa_Model_CategoryGateway extends Sherpa_Model_BaseGateway
{

	/**
	 * @param integer $id
	 * @param integer $languageId
	 * @return Sherpa_Model_Category
	 */
	public function fetchById($id, $languageId)
	{
		$db = $this->getDb();
		$stmt = $db->query('SELECT * FROM sherpa_categories WHERE id=? AND languageId=? AND hidden=0', array($id, $languageId));
		if ($row = $stmt->fetch()) {
			return new Sherpa_Model_Category($row);
		}
		return null;
	}

	/**
	 * @param integer $languageId
	 * @return Sherpa_Model_Categories
	 */
	public function fetchAll($languageId)
	{
		$db = $this->getDb();
		$stmt = $db->query('SELECT * FROM sherpa_categories WHERE languageId = ? AND hidden=0 ORDER BY sort ASC', array($languageId));
		return new Sherpa_Model_Categories($stmt->fetchAll());
	}

	/**
	 * @param integer $languageId
	 * @param integer $parentId
	 * @return Sherpa_Model_Categories
	 */
	public function fetchByParentId($languageId, $parentId)
	{
		$db = $this->getDb();
		$parentId = intval($parentId);
		if(empty($parentId)) {
			$stmt = $db->query('SELECT * FROM sherpa_categories WHERE parentId IS NULL AND languageId = ? AND hidden=0 ORDER BY sort ASC', array($languageId));
		} else {
			$stmt = $db->query('SELECT * FROM sherpa_categories WHERE parentId=? AND languageId = ? AND hidden=0 ORDER BY sort ASC', array($parentId, $languageId));
		}
		return new Sherpa_Model_Categories($stmt->fetchAll());
	}

	/**
	 * @param integer $languageId
	 * @return Sherpa_Model_Categories
	 */
	public function fetchLevelOneItems($languageId)
	{
		$db = $this->getDb();
		$languageId = intval($languageId);
		$stmt = $db->query('SELECT * FROM sherpa_categories WHERE parentId IS NULL AND languageId = ? AND hidden=0 ORDER BY sort ASC', array($languageId));
		return new Sherpa_Model_Categories($stmt->fetchAll());
	}

	/**
	 * @param integer $languageId
	 * @return array
	 */
    public function fetchTree($languageId)
    {
        require_once(WSB_MODULES_PATH .'sherpa/models/CategoryTree.php');
		$db = $this->getDb();
		$stmt = $db->query('SELECT * FROM sherpa_categories WHERE languageId = ? AND hidden=0 ORDER BY sort ASC', array($languageId));
		return new Sherpa_Model_CategoryTree($stmt->fetchAll());
    }

}
